﻿
using AutoMapper;
using MediatR;
using AutoMapper;using MediatR;
using Microsoft.EntityFrameworkCore;
using Warehouse.API.Applcation.Command.AllocateCommand;
using Warehouse.Domain;
using Warehouse.Infrstructre;
using Warehouse.Infrstructre.Interface;

namespace Warehouse.API.Applcation.CommandHandlers.AllocateCommandHandlers
{
    public class AllocateAddCommandHandlers : IRequestHandler<AllocateAddCommand, int>
    {
        private readonly IAllocateRepository _allocateRepository;
        protected readonly EFCoreDBcontext _dbContext;
        private readonly IMapper _mapper;
        private readonly IAllProductRepsitory _allProductRepsitory;
        public AllocateAddCommandHandlers(IAllocateRepository _allocateRepository, IAllProductRepsitory _allProductRepsitory, IMapper _mapper, EFCoreDBcontext _dbContext)
        {
            this._allocateRepository = _allocateRepository;
            this._allProductRepsitory = _allProductRepsitory;
            this._mapper = _mapper;
            this._dbContext = _dbContext;
        }
        public async Task<int> Handle(AllocateAddCommand request, CancellationToken cancellationToken)
        {
            using (var tran = await _dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {

                try
                {
                    var s = _mapper.Map<Allocate>(request.addDto);

                    // 先处理 procurement1
                    await _allocateRepository.AddAsync(s);

                    foreach (var item in request.addDto.AllProducs)
                    {
                        AllProduct detail = new AllProduct
                        {
                            ProductsID = item.ProductsID,
                            AllocateId = s.AllocateId,
                            AllProductNum=item.AllProductNum,
                            StorehouseId = item.StorehouseId,
                            office_id = s.office_id,
                            user_id = s.user_id,

                        }; 
                        await _allProductRepsitory.AddAsync(detail);
                    }

                    // 提交事务
                    await tran.CommitAsync();

                                         return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    await tran.RollbackAsync();
                    throw;
                }
            }
        }
    }
}
